<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Api\Controllers\Auths;

use App\Api\BaseApi;
use App\Jobs\CartOrderPlacementJob;
use App\Models\Cart;
use App\Models\Product;
use App\Models\ProductOrder;
use App\Service\AdvanceCard\AdvanceCardService;
use App\Service\Pools\DividendService;
use App\Service\Product\ProductOrderService;
use App\Service\User\PerformanceService;
use App\Service\User\WalletAccountService;

class ProductApi extends BaseApi
{
    public function orderPlacement()//订单下单
    {
        $request = self::validate([
            'product_id' => 'required|integer',
            'sku' => 'required|array',
            'quantity' => 'required|integer|min:1',
            'method' => 'required|in:1,2',
        ]);
        $sku = $request->get('sku');
        $productOrder = ProductOrder::query()->create([
            'order_no' => genOrderNumber('P'),
            'user_id' => self::UserId(),
            'product_id' => $request->get('product_id'),
            'type' => 1,
            'total_amount' => bcmul($request->get('quantity'), $sku['member_price'], 2),
            'price' => $sku['member_price'],
            'number' => $request->get('quantity'),
            'sku' => $request->get('sku'),
            'method' => $request->get('method'),
            'status' => 1,
        ]);
        return responses($productOrder);
    }

    public function payAndPlaceAnOrder() // 订单支付
    {
        $request = self::validate([
            'product_order_id' => 'required|exists:product_orders,id',
            'transaction_password' => 'required',
        ]);
        $order = ProductOrder::query()
            ->where('user_id', self::UserId())
            ->find($request['product_order_id']);
        if (blank($order)) {
            return responses('无效的订单', 7);
        }
        $quantity = $order->number;
        $user = self::UserModel(['address']);
        $method = $order->method;
        if (blank($user->transaction_password) || ! password_verify($request->get('transaction_password'), $user->transaction_password)) {
            return responses('交易密码错误或未设置！', 7);
        }
        $product = Product::query()
            ->where('status', 1)
            ->find($order->product_id);
        if (blank($product)) {
            return responses('未找到该商品', 7);
        }
        $address = $user->address->id ?? null;
        if (blank($address)) {
            return responses('未绑定默认收获地址！', 7);
        }
        $productSku = $product->sku;
        [$key, $sku] = searchArrayInMulti($order->sku, $productSku['sku'], ['stock']);
        if (! $sku) {
            return responses('无效的sku', 7);
        }
        //TODO 计算sku库存
        $sku['stock'] = $sku['stock'] - $quantity;
        if ($sku['stock'] < 0) {
            return responses('库存不足', 7);
        }
        $productSku['sku'][$key] = $sku;
        $product->sku = json_encode($productSku);
        $amount = bcmul($sku['member_price'], $quantity, 2);
        $order->total_amount = $amount;
        $order->price = $sku['member_price'];
        $order->sku = $sku;
        $order->save();
        $wall = WalletAccountService::make()->consumption($user->id, $amount);
        if (! $wall) {
            return responses('钱包余额不足！', 7);
        }


        //TODO 减库存
        $product->sku = json_encode($productSku);
        $product->stock -= $quantity;
        $product->sold_num += $quantity;
        $product->save();
        ProductOrderService::make()->placeAnOrder($user, $order, $method);

//        DividendService::make()->injectFunds($amount, 2); //进入分红池
        //用户树收益
        PerformanceService::make()->userTreeRevenue($user, $amount);
        //业绩奖励
        PerformanceService::make()->performanceReward($user, $amount);
        $user->increment('inject_integral',$amount * 2);

        return responses('下单成功');
    }

    public function cartOrderPlacement() //购物车下单
    {
        $request = self::validate([
            'ids' => 'required|array',
            'transaction_password' => 'required',
            'method' => 'required|in:1,2',
        ]);

        $cart = Cart::with(['product' => function ($query) {
            $query->select(['id', 'sold_num', 'stock', 'sku', 'status', 'name']);
        }])
            ->where('is_valid', 1)
            ->whereIn('id', $request->get('ids'))
            ->get();
        if (blank($cart)) {
            return responses('无效的购物车ID', 7);
        }
        $user = self::UserModel(['address']);
        if (blank($user->transaction_password) || ! password_verify($request->get('transaction_password'), $user->transaction_password)) {
            return responses('交易密码错误或未设置！', 7);
        }
        if (blank($user->address)) {
            return responses('未指定默认收货地址！', 7);
        }
        $countPrice = 0;
        //更新SKU
        $cart->each(function ($item) use (&$countPrice) {
            if (blank($item->product)) {
                $item->delete();
                $this->exit('商品不存在,下单失败！已从购物车删除.', 7);
            } else {
                if ($item->product->status != 1) {
                    $item->delete();
                    $this->exit('商品已下架,下单失败！已从购物车删除.', 7);
                }
            }
            $productSku = $item->product->sku;
            //sku对比
            [$key, $sku] = searchArrayInMulti($item->sku, $productSku['sku'], ['stock']);
            if (! $sku) {
                $item->delete();
                $this->exit(sprintf('下单失败,商品:%s 无效的规格！已从购物车删除.', $item->product->name), 7);
            }
            if ($sku['stock'] < $item->quantity) {
                $item->delete();
                $this->exit(sprintf('下单失败,该规格商品:%s 库存不足！已从购物车删除.', $item->product->name), 7);
            } else {
                //减库存 下单
                if ($item->price != $sku['member_price']) {
                    $item->price == $sku['member_price'];
                    $item->save();
                }
            }
            $countPrice = bcadd($countPrice, bcmul($sku['member_price'], $item->quantity, 2), 2);
        });

        $wall = WalletAccountService::make()->checkTheBalance(self::UserId());
        if ($wall < $countPrice) {
            $this->exit('钱包余额不足！下单失败！', 7);
        }

//        //TODO检验完成 交给队列
        CartOrderPlacementJob::dispatch($user, $cart, $request->get('method'))
            ->onQueue('cart_order_placement');
        return responses('下单成功！');
    }
}
